import { TtMemberInfoType } from "@/alipayApiTypes";

interface UserProType {
  encryptedData: string;
  errMsg: string;
  iv: string;
  rawData: string;
  signature: string;
  userInfo: {
    avatarUrl: string;
    city: string;
    country: string;
    gender: 0 | 1;
    language: string;
    nickName: string;
    province: string;
  };
}

type Option = {
  success?: (res: any) => void;
  fail?: (e: any) => void;
};

type CheckShopMemberOption = {
  shopId: string;
  success?: (res: any) => void;
  fail?: (e: any) => void;
};

type CalendarOption = {
  title: string;
  startTime: number;
  endTime: number;
  description: string;
  success?: (res: any) => void;
  fail?: (e: any) => void;
};

type AuthOption = {
  success?: (res: any) => void;
  fail?: (e: any) => void;
  scope: string;
};

type ChangePointType = {
  shopId: string;
  updateInfo: {
    type: number;
    amount: number;
    recordToken: string;
  };
  fail?: (e: any) => void;
  success?: (res: any) => void;
};

type RecordTokenType = {
  shopId: string;
  type: 1;
  fail?: (e: any) => void;
  success?: (res: any) => void;
};

type OpenEcGoodType = {
  promotionId: string;
  fail?: (e: any) => void;
  success?: (res: any) => void;
};

type ExclusivePriceType = {
  shopId: string;
  activityId: string;
  buyLimit: number;
  fail?: (e: any) => void;
  success?: (res: any) => void;
};

type OpenEcImType = {
  promotionId?: string;
  orderId?: string;
  shopId: string;
  fail?: (e: any) => void;
  success?: (res: any) => void;
};

type tt = {
  openEcIm: (OpenEcImType: OpenEcImType) => Promise<Record<string, any>>;
  registerExclusivePriceActivity: (ExclusivePriceType: ExclusivePriceType) => Promise<Record<string, any>>;
  openEcGood: (OpenEcGoodType: OpenEcGoodType) => Promise<Record<string, any>>;
  openSetting: (Option: Option) => void;
  setSwipeBackMode: (number) => void;
  login: (LoginOption: Option) => Promise<string>;
  authorize: (AuthOption: AuthOption) => Promise<boolean>;
  addPhoneCalendar: (CalendarOption: CalendarOption) => Promise<boolean>;
  openEcMemberCenter: (CheckShopMemberOption: CheckShopMemberOption) => void;
  checkShopMember: (CheckShopMemberOption: CheckShopMemberOption) => Promise<boolean>;
  getShopMemberInfo: (CheckShopMemberOption: CheckShopMemberOption) => Promise<TtMemberInfoType>;
  updateShopMemberPoints: (ChangePointType: ChangePointType) => Promise<void>;
  getShopRecordToken: (RecordTokenType: RecordTokenType) => Promise<string>;
};

/**
 * 跳转店铺同步
 * @param shopId 当前小程序绑定的抖音小店 id
 * @param tabType 指定跳转店铺 tab 页，默认为商品tab 1精选 2分类 3商品 4大促 5旧ISV 6会员 7新 ISV
 * @returns
 */
export const openEcShopSync = (shopId: string, tabType?: 1 | 2 | 3 | 4 | 5 | 6 | 7) => {
  return new Promise(resolve => {
    if (!tt.canIUse("openEcShop")) {
      resolve({
        status: false,
        msg: "版本不足",
        errNo: 401,
      });
    }
    try {
      tt.openEcShop({
        shopId: shopId,
        tabType: tabType || 1,
        success: res => {
          resolve({
            status: true,
            msg: res.errMsg,
          });
        },
        fail: res => {
          resolve({
            status: false,
            msg: res.errMsg,
            errNo: res.errNo,
          });
        },
        complete: () => {
          void 0;
        },
      });
    } catch (error) {
      resolve({
        status: false,
        msg: "请求错误",
      });
    }
  });
};

/**
 * 获取用户信息
 * @param force  当宿主未登录时，是否强制拉起登录框
 * @returns {Object}
 * {
 *
 * encryptedData: string ,//已加密用户数据，不包含 openId、unionId
 *
 * errMsg: string,// "getUserProfile:ok"
 *
 * iv: string,//加密算法参数
 *
 * rawData: string,//userInfo 的 JSON 字符串形式
 *
 *  signature: string,//userInfo 的 JSON 字符串形式
 *
 *   userInfo://userInfo 的 JSON 字符串形式
 *
 * {
 *
 *    avatarUrl: string;//用户头像
 *
 *    city: string;//用户城市
 *
 *    country: string;//用户国家
 *
 *    gender: 0 | 1 | 2;//用户性别，0: 未知；1:男性；2:女性
 *
 *    language: string;//用户语言，目前为空
 *
 *    nickName: string;//	用户昵称
 *
 *    province: string;//用户省份
 *
 *    },
 *
 * }
 *
 *
 */
export const getUserProfileSync = async (force: boolean): Promise<UserProType> => {
  return new Promise((resolve, reject) => {
    tt.getUserProfile({
      force: force,
      success: res => {
        resolve(res as UserProType);
      },
      fail: res => {
        reject(res);
      },
      complete(res: any) {
        console.log("getUserProfile", res);
      },
    });
  });
};
/**
 * 用户拍抖音授权
 * @param scopes 需要获取权限的信息，其中 key 值是申请权限的 scope，value 值必须是 0，1，2（此处申请的权限在抖音开放平台必须是已开通状态）
 * @returns
 */
export const showDouyinOpenAuthSync = (scopes: { [key: string]: 0 | 1 | 2 }): Promise<{ ticket: string }> => {
  return new Promise((resolve, reject) => {
    tt.showDouyinOpenAuth({
      scopes: scopes,
      success(res) {
        console.log("showDouyinOpenAuth", res);
        resolve(res);
      },
      fail(res) {
        console.log("showDouyinOpenAuth", res);
        reject(res);
      },
      complete(res: any) {
        console.log("showDouyinOpenAuth", res);
      },
    });
  });
};
/**
 * 检查店铺会员
 * @param shopId 当前小程序绑定的抖音小店id
 * @returns
 */
export const checkShopMemberSync = (shopId: string): Promise<{ stauts: boolean; isMember: boolean }> => {
  return new Promise(resolve => {
    tt.checkShopMember({
      shopId: shopId,
      success(res) {
        console.log(res);

        resolve({
          stauts: true,
          isMember: res.isMember,
        });
      },
      fail(res) {
        console.log(res);
        resolve({
          stauts: false,
          isMember: res,
        });
      },
      complete(res: any) {
        console.log("checkShopMember", shopId, res);
      },
    });
  });
};
/**
 * 领取优惠券
 * @param obj
 * @param obj.shopId 当前小程序绑定的抖音小店id
 * @param obj.couponMetaId 本次发放券的券批次id
 * @param obj.couponCount 本次发放券的券数量
 * @returns
 */

export const applyEcCouponSync = (obj: {
  shopId: string;
  /**本次发放券的券批次id */
  couponMetaId: string;
  /**本次发放券的券数量 */
  couponCount: number;
}): Promise<Record<string, any>> => {
  return new Promise((resolve, reject) => {
    tt.applyEcCoupon({
      ...obj,
      success(res) {
        resolve(res);
      },
      fail(res) {
        reject(res);
      },
      complete(res: any) {
        console.log("applyEcCoupon", res);
      },
    });
  });
};
/**
 * 小程序跳转到小店购物车
 * @param shopId 当前小程序绑定的抖音小店 id
 * @param type 跳转购物车类型1 ：跳转全局购物车（ 暂时只支持传1 ）2 ： 跳转单店购物车
 * @param selectedType 跳转购物车后默认选中类型，不传入表示没有选中商品1 ：选中本店店铺的所有商品2：选中指定加购后的商品，需要传入 cartIds
 * @param cartIds 跳转后选中的 cartId， cartId是在调用tt.addToEcCart 成功后生成的cardId  ["xxxxxx","xxxxxx"]
 * @returns
 */
export const openEcCartSync = (obj: { shopId: string; type: 1 | 2; selectedType: 1 | 2; cartIds: Array<string> }) => {
  return new Promise(resolve => {
    if (!tt.canIUse("openEcCart")) {
      resolve({
        status: false,
        msg: "版本不足",
        errNo: 401,
      });
    }
    try {
      tt.openEcCart({
        ...obj,
        success: res => {
          resolve({
            status: true,
            msg: res.errMsg,
          });
        },
        fail: res => {
          resolve({
            status: false,
            msg: res.errMsg,
            errNo: res.errNo,
          });
        },
        complete: () => {
          void 0;
        },
      });
    } catch (error) {
      resolve({
        status: false,
        msg: "请求错误",
      });
    }
  });
};

/**
 *小程序跳转到抖音小店提交订单页
 * @param shopId 当前小程序绑定的抖音小店id
 * @param productId 当前小程序提交订单的商品id
 * @param skuId 当前小程序提交订单的商品skuId
 * @param skuAmount 当前小程序提交订单的商品sku的数量
 * @returns
 */
export const openEcOrderSync = (obj: { shopId: string; productId: string; skuId: string; skuAmount: number }) => {
  return new Promise(resolve => {
    if (!tt.canIUse("opopenEcOrderenEcCart")) {
      resolve({
        status: false,
        msg: "版本不足",
        errNo: 401,
      });
    }
    try {
      tt.openEcOrder({
        ...obj,
        success: res => {
          resolve({
            status: true,
            msg: res.errMsg,
          });
        },
        fail: res => {
          resolve({
            status: false,
            msg: res.errMsg,
            errNo: res.errNo,
          });
        },
        complete: () => {
          void 0;
        },
      });
    } catch (error) {
      resolve({
        status: false,
        msg: "请求错误",
      });
    }
  });
};
/**
 *
 * @param obj
 * @param tmplIds 需要订阅的消息模板的 id 的集合，最多支持传入三个 tmplId
 * @returns
 */
export const requestSubscribeMessageSync = (obj: { tmplIds: string[] }) => {
  return new Promise(resolve => {
    if (!tt.canIUse("requestSubscribeMessage")) {
      resolve({
        status: false,
        msg: "版本不足",
        errNo: 401,
      });
    }
    try {
      tt.requestSubscribeMessage({
        ...obj,
        success: res => {
          resolve({
            status: true,
            msg: res.errMsg,
          });
        },
        fail: res => {
          resolve({
            status: false,
            msg: res.errMsg,
            errNo: res.errNo,
          });
        },
        complete: () => {
          void 0;
        },
      });
    } catch (error) {
      resolve({
        status: false,
        msg: "请求错误",
      });
    }
  });
};

/*
    @name: getServerTime
    @author: zhangzw
    @date: 2024-01-22 09:29:40
    @LastEditors:zhangzw
    @LastEditTime:2024-01-22 09:29:40
    @params:
    @return:当前时间戳
    @description: 获取服务器时间
*/
export const ttLogin = (): Promise<string> => {
  return new Promise((resolve, reject) => {
    (tt as unknown as tt).login({
      success: res => {
        resolve(res.code);
      },
      fail: res => {
        reject(res);
      },
    });
  });
};

/*
    @name: getServerTime
    @author: zhangzw
    @date: 2024-01-22 09:29:40
    @LastEditors:zhangzw
    @LastEditTime:2024-01-22 09:29:40
    @params:
    @return:当前时间戳
    @description: 获取服务器时间
*/
export const checkMember = (params: { shopId: string }): Promise<boolean> => {
  return new Promise((resolve, reject) => {
    (tt as unknown as tt).checkShopMember({
      shopId: params.shopId,
      success: res => {
        resolve(res.isMember);
      },
      fail: res => {
        reject(res);
      },
    });
  });
};

/*
    @name: getServerTime
    @author: zhangzw
    @date: 2024-01-22 09:29:40
    @LastEditors:zhangzw
    @LastEditTime:2024-01-22 09:29:40
    @params:
    @return:获取积分
    @description: 获取服务器时间
*/
export const getMemberInfo = (params: { shopId: string }): Promise<TtMemberInfoType> => {
  return new Promise((resolve, reject) => {
    (tt as unknown as tt).getShopMemberInfo({
      shopId: params.shopId,
      success: (res: { memberCardInfo: TtMemberInfoType }) => {
        resolve(res.memberCardInfo);
      },
      fail: res => {
        reject(res);
      },
    });
  });
};

/*
    @name: getServerTime
    @author: zhangzw
    @date: 2024-01-22 09:29:40
    @LastEditors:zhangzw
    @LastEditTime:2024-01-22 09:29:40
    @params:
    @return:获取积分
    @description: 获取服务器时间
*/
export const openMemberCenter = (params: { shopId: string }) => {
  (tt as unknown as tt).openEcMemberCenter({
    shopId: params.shopId,
    success: () => {},
    fail: () => {},
  });
};

/*
    @name: getServerTime
    @author: zhangzw
    @date: 2024-01-22 09:29:40
    @LastEditors:zhangzw
    @LastEditTime:2024-01-22 09:29:40
    @params:
    @return:获取积分
    @description: 获取服务器时间
*/
export const addTtCalendar = (params: {
  title: string;
  startTime: number;
  endTime: number;
  description: string;
}): Promise<boolean> => {
  return new Promise((resolve, reject) => {
    (tt as unknown as tt).addPhoneCalendar({
      ...params,
      success: res => {
        if (res.errMsg == "addPhoneCalendar:ok") {
          resolve(true);
        } else {
          reject();
        }
      },
      fail: () => {
        reject();
      },
    });
  });
};

/*
    @name: getServerTime
    @author: zhangzw
    @date: 2024-01-22 09:29:40
    @LastEditors:zhangzw
    @LastEditTime:2024-01-22 09:29:40
    @params:
    @return:获取积分
    @description: 获取服务器时间
*/
export const authTtCalendar = (): Promise<boolean> => {
  return new Promise((resolve, reject) => {
    (tt as unknown as tt).authorize({
      scope: "scope.calendar",
      success: res => {
        console.log(res, "eee");
        if (res.data["scope.calendar"] == "ok") {
          resolve(true);
        } else {
          reject();
        }
      },
      fail: err => {
        console.log(err, "err");
        reject();
      },
    });
  });
};

/*
    @name: getServerTime
    @author: zhangzw
    @date: 2024-01-22 09:29:40
    @LastEditors:zhangzw
    @LastEditTime:2024-01-22 09:29:40
    @params:
    @return:获取积分
    @description: 获取服务器时间
*/
export const openTtSetting = () => {
  (tt as unknown as tt).openSetting({
    success: () => {},
    fail: () => {},
  });
};

/*
    @name: getServerTime
    @author: zhangzw
    @date: 2024-01-22 09:29:40
    @LastEditors:zhangzw
    @LastEditTime:2024-01-22 09:29:40
    @params:
    @return:获取积分
    @description: 获取服务器时间
*/
export const changeTtPoint = (params: {
  shopId: string;
  updateInfo: {
    type: number;
    amount: number;
    recordToken: string;
  };
}): Promise<void> => {
  return new Promise((resolve, reject) => {
    (tt as unknown as tt).updateShopMemberPoints({
      ...params,
      success: () => {
        resolve();
      },
      fail: err => {
        reject(err);
      },
    });
  });
};

/*
    @name: getServerTime
    @author: zhangzw
    @date: 2024-01-22 09:29:40
    @LastEditors:zhangzw
    @LastEditTime:2024-01-22 09:29:40
    @params:
    @return:获取积分
    @description: 获取服务器时间
*/
export const getRecordToken = (params: { shopId: string; type: 1 }): Promise<string> => {
  return new Promise((resolve, reject) => {
    (tt as unknown as tt).getShopRecordToken({
      ...params,
      success: res => {
        resolve(res.recordToken);
      },
      fail: err => {
        reject(err);
      },
    });
  });
};

/*
    @name: getServerTime
    @author: zhangzw
    @date: 2024-01-22 09:29:40
    @LastEditors:zhangzw
    @LastEditTime:2024-01-22 09:29:40
    @params:
    @return:获取积分
    @description: 获取服务器时间
*/
export const setSwipeBackMode = () => {
  (tt as unknown as tt).setSwipeBackMode(0);
};

/*
    @name: getServerTime
    @author: zhangzw
    @date: 2024-01-22 09:29:40
    @LastEditors:zhangzw
    @LastEditTime:2024-01-22 09:29:40
    @params:
    @return:获取积分
    @description: 获取服务器时间
*/
export const openGoodsDetail = (goodsId: string): Promise<Record<string, any>> => {
  return new Promise((resolve, reject) => {
    (tt as unknown as tt).openEcGood({
      promotionId: goodsId,
      success: res => {
        resolve(res);
      },
      fail: err => {
        reject(err);
      },
    });
  });
};

/*
    @name: getServerTime
    @author: zhangzw
    @date: 2024-01-22 09:29:40
    @LastEditors:zhangzw
    @LastEditTime:2024-01-22 09:29:40
    @params:
    @return:获取积分
    @description: 获取服务器时间
*/
export const ttMark = (params: { shopId: string; activityId: string; buyLimit: 1 }): Promise<Record<string, any>> => {
  return new Promise((resolve, reject) => {
    (tt as unknown as tt).registerExclusivePriceActivity({
      ...params,
      success: res => {
        resolve(res);
      },
      fail: err => {
        if (err.errMsg.indexOf("系统错误") != -1) {
          ttMark(params);
        } else if (err.errMsg.indexOf("当前用户已完成过活动注册") != -1) {
          ttMark(params);
        } else {
          reject(err);
        }
      },
    });
  });
};

/*
    @name: getServerTime
    @author: zhangzw
    @date: 2024-01-22 09:29:40
    @LastEditors:zhangzw
    @LastEditTime:2024-01-22 09:29:40
    @params:
    @return:获取积分
    @description: 获取服务器时间
*/
export const ttOpenCustomer = (params: {
  promotionId?: string;
  orderId?: string;
  shopId: string;
}): Promise<Record<string, any>> => {
  return new Promise((resolve, reject) => {
    (tt as unknown as tt).openEcIm({
      ...params,
      success: res => {
        resolve(res);
      },
      fail: err => {
        reject(err);
      },
    });
  });
};
